let path = require('path');
let glob = require('glob');

// 工厂函数 - 配置pages实现多页面获取某文件夹下的html与js
function handleEntry(entry) {
  let entries = {}
  let entryBaseName = ''
  let entryPathName = ''
  let entryTemplate = ''
  let applicationName = ''

  glob.sync(entry).forEach(item => {
    console.log('!!!', item)
    entryBaseName = path.basename(item, path.extname(item))
    console.log('entryBaseName:', entryBaseName)
    entryTemplate = item.split('/').splice(-3)
    console.log('entryTemplate:', entryTemplate)
    entryPathName = entryBaseName // 正确输出js和html的路径
    console.log('entryPathName', entryPathName)

    entries[entryPathName] = {
      entry: 'src/' + entryTemplate[0] + '/' + entryTemplate[1] + '/' + entryTemplate[1] + '.js',
      template: 'src/' + entryTemplate[0] + '/' + entryTemplate[1] + '/' + entryTemplate[2],
      title: entryTemplate[2],
      filename: entryTemplate[2]
    }
  })

  return entries
}

// 页面地址数组
let pages = handleEntry('./src/pages/**?/*.html')

module.exports = {
  devServer: {
    index: '/', // 运行时，默认打开index页面
    // 告诉dev-server在服务器启动后打开浏览器，将其设置true为打开默认浏览器
    open: true,
    host: 'localhost',
    port: 8080,
    https: false,
    hotOnly: false,
    // 配置首页 入口链接
    before: app => {
      app.get('/', (req, res, next) => {
        for (let i in pages) {
          res.write(`<a target="_self" href="/${i}">/${i}</a></br>`);
        }
        res.end()
      });
    },
    // 设置代理地址
    /* proxy: {
      '/api': {
        target: 'http://www.liulongbin.top:3005/',
        changeOrigin: true,
        ws: true
      }
    } */
  },
  // 所有的资源都会被链接为相对路径
  publicPath: process.env.NODE_ENV === "production" ? "./" : "/",
  productionSourceMap: false,
  pages
}
